package org.dromara.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.admin.domain.Employee;
import org.dromara.admin.domain.TemplateMarket;
import org.dromara.admin.domain.vo.EmployeeVo;
import org.dromara.admin.service.IEmployeeService;
import org.dromara.admin.service.ITemplateMarketService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.CollectTemplateBo;
import org.dromara.admin.domain.vo.CollectTemplateVo;
import org.dromara.admin.domain.CollectTemplate;
import org.dromara.admin.mapper.CollectTemplateMapper;
import org.dromara.admin.service.ICollectTemplateService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 用户收藏模板Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-17
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class CollectTemplateServiceImpl implements ICollectTemplateService {

    private final CollectTemplateMapper baseMapper;
    private final IEmployeeService employeeService;
    private final ITemplateMarketService templateMarketService;

    /**
     * 查询用户收藏模板
     *
     * @param id 主键
     * @return 用户收藏模板
     */
    @Override
    public CollectTemplateVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户收藏模板列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户收藏模板分页列表
     */
    @Override
    public TableDataInfo<CollectTemplateVo> queryPageList(CollectTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CollectTemplate> lqw = buildQueryWrapper(bo);
        Page<CollectTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询当前用户主体的收藏模板列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return
     */
    @Override
    public TableDataInfo<CollectTemplateVo> queryPageMyCollectTemplateList(CollectTemplateBo bo, PageQuery pageQuery) {
        EmployeeVo employeeVo = employeeService.queryById(bo.getCompanyId());
        bo.setCompanyId(employeeVo.getCompanyId());
        MPJLambdaWrapper<CollectTemplate> mpjWrapper = getCollectTemplateInfoByJoinTable(bo);
        Page<CollectTemplateVo> result = baseMapper.selectJoinPage(pageQuery.build(), CollectTemplateVo.class, mpjWrapper);
        return TableDataInfo.build(result);
    }

    /**
     * 联表查询collectTemplate、templateMarket和employee表
     */
    private static MPJLambdaWrapper<CollectTemplate> getCollectTemplateInfoByJoinTable(CollectTemplateBo bo) {
        // 使用MPJBaseMapper进行联表查询collectTemplate、templateMarket和employee表
        MPJLambdaWrapper<CollectTemplate> mpjWrapper = new MPJLambdaWrapper<CollectTemplate>()
            .selectAll(CollectTemplate.class)
            .selectAssociation(TemplateMarket.class, CollectTemplateVo::getTemplateInfo)
            .selectAssociation(Employee.class, CollectTemplateVo::getEmployeeInfo)
            .leftJoin(TemplateMarket.class, TemplateMarket::getId, CollectTemplate::getTemplateId)
            .leftJoin(Employee.class, Employee::getId, CollectTemplate::getEmployeeId)
            .orderByDesc(CollectTemplate::getCreateTime)
            .like(StrUtil.isNotBlank(bo.getTemplateName()), TemplateMarket::getTemplateName, bo.getTemplateName())
            .eq(bo.getCategory() != null, TemplateMarket::getCategory, bo.getCategory())
            .eq(bo.getEmployeeId() != null, CollectTemplate::getEmployeeId, bo.getEmployeeId())
            .eq(bo.getCompanyId() != null, CollectTemplate::getCompanyId, bo.getCompanyId())
            .eq(bo.getTemplateId() != null, CollectTemplate::getTemplateId, bo.getTemplateId());
        return mpjWrapper;
    }

    /**
     * 查询符合条件的用户收藏模板列表
     *
     * @param bo 查询条件
     * @return 用户收藏模板列表
     */
    @Override
    public List<CollectTemplateVo> queryList(CollectTemplateBo bo) {
        LambdaQueryWrapper<CollectTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CollectTemplate> buildQueryWrapper(CollectTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CollectTemplate> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(CollectTemplate::getCreateTime);
        lqw.eq(bo.getEmployeeId() != null, CollectTemplate::getEmployeeId, bo.getEmployeeId());
        lqw.eq(bo.getCompanyId() != null, CollectTemplate::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getTemplateId() != null, CollectTemplate::getTemplateId, bo.getTemplateId());
        return lqw;
    }

    /**
     * 新增用户收藏模板
     *
     * @param bo 用户收藏模板
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(CollectTemplateBo bo) {
        CollectTemplate add = MapstructUtils.convert(bo, CollectTemplate.class);
        EmployeeVo employeeVo = employeeService.queryById(bo.getEmployeeId());
        add.setCompanyId(employeeVo.getCompanyId());

        // 查询模版信息，更新模板被收藏次数+1
        templateMarketService.addTemplateCollectCount(bo.getTemplateId());

        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户收藏模板
     *
     * @param bo 用户收藏模板
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(CollectTemplateBo bo) {
        CollectTemplate update = MapstructUtils.convert(bo, CollectTemplate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CollectTemplate entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户收藏模板信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        if (CollUtil.isEmpty(ids)) {
            throw new ServiceException("要删除的收藏记录不能为空！");
        }

        // 查询这些收藏记录对应的模板ID
        List<Long> templateIds = baseMapper.selectList(
            new LambdaQueryWrapper<CollectTemplate>()
                .in(CollectTemplate::getId, ids)
                .select(CollectTemplate::getTemplateId)
        ).stream().map(CollectTemplate::getTemplateId).collect(Collectors.toList());
        if (CollUtil.isEmpty(templateIds)) {
            throw new ServiceException("未找到对应的模板记录！");
        }

        boolean b = baseMapper.deleteByIds(ids) > 0;
        if (!b) {
            throw new ServiceException("取消收藏模版失败！");
        }

        // 取消收藏成功后，更新模版被收藏次数-1
        for (Long templateId : templateIds) {
            templateMarketService.reduceTemplateCollectCount(templateId);
        }
        return Boolean.TRUE;
    }

    /**
     * 判断用户的主体公司是否收藏了该模板
     *
     * @param userId     用户ID
     * @param templateId 模版ID
     * @return 是否收藏
     */
    @Override
    public Boolean isCollect(Long userId, Long templateId) {
        // 查询模版信息
        templateMarketService.queryById(templateId);
        // 获取主体公司ID
        Long companyId = employeeService.queryById(userId).getCompanyId();
        return baseMapper.exists(
            new LambdaQueryWrapper<CollectTemplate>()
                .eq(CollectTemplate::getCompanyId, companyId)
                .eq(CollectTemplate::getTemplateId, templateId)
        );
    }
}
